﻿
namespace StudentManegement.Models
{
    public class SQLStudentRepository : IStudentRepository
    {
        public readonly AppDBContext context;
        private readonly ILogger logger;

        public SQLStudentRepository(AppDBContext context,ILogger<SQLStudentRepository> logger)
        {
            this.context = context;
            this.logger = logger;
        }


        public StudentModel CreatStudent(StudentModel student)
        {
            context.Students.Add(student);
            context.SaveChanges();
            return student;
        }

        public StudentModel DeleteStudent(int id)
        {
            StudentModel student = context.Students.FirstOrDefault(e => e.Id == id);
            if (student != null)
            {
                context.Students.Remove(student);
            }

            return student;
        }

        public IEnumerable<StudentModel> GetAllStudents()
        {
            return context.Students;
        }

        public StudentModel GetStudentModel(int id)
        {
            logger.LogTrace("学生信息 Trace(跟踪) Log");
            logger.LogDebug("学生信息 Debug(调试) Log");
            logger.LogInformation("学生信息 信息(Information) Log");
            logger.LogWarning("学生信息 警告(Warning) Log");
            logger.LogError("学生信息 错误(Error) Log");
            logger.LogCritical("学生信息 严重(Critical) Log");

            return context.Students.Find(id);
        }

        public StudentModel updateStudent(StudentModel updateStudent)
        {
            var student = context.Students.Attach(updateStudent);
            student.State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            context.SaveChanges();
            return updateStudent;
        }
    }
}
